<?php
declare (strict_types = 1);
namespace app\admin\model;
use app\admin\model\AdminUserRole as AdminUserRoleModel;
use app\admin\model\AdminRoleMenu as AdminRoleMenuModel;
/**
 * 超管角色列表模型
 */
class AdminRole extends BaseModel
{
	
	// 定义表名
    protected $name = 'admin_role';

    // 定义主键
    protected $pk = 'admin_role_id';

    // 追加字段
    // protected $append = [''];
    
    /**
     * [filter 查询条件过滤器]
     * Author：上官钧墨
     * @return $data [被过滤数组]
     */
    private function filter($data=[])
    {
 		// 设置要查询的字段
    	$default = [
    		'admin_role_id'=>'',
    		'role_name'=>'',
    		'pid'=>'',
    	];
    	if (count($data)<1) {
    		return [];
    	}
    	// 合并数据，以设置为准
    	$params = $this->setDefaultValue($data,$default);
    	$filter = [];
    	// 更多查询条件......
    	!empty($params['admin_role_id']) && $filter[] = ['admin_role_id', '=', $params['admin_role_id']];
    	!empty($params['pid']) && $filter[] = ['pid', '=', $params['pid']];
        !empty($params['role_name']) && $filter[] = ['role_name', 'like', "%{$params['role_name']}%"];

        return $filter;

    }

    /**
     * [getList 获取菜单树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function getList($data)
    {
        $hidden = ['create_time','update_time'];
        $page = 1;//设置页码
		$listRows = 15;//设置每页条数

		isset($data['page']) && !empty((int)$data['page'])?$page = $data['page']:$page;
		isset($data['listRows']) && !empty((int)$data['listRows'])?$page = $data['listRows']:$page;

		$model = $this->where($this->filter($data));
		$total = $model->count();
        $list = $model->page($page,$listRows)->select();

        $RoleMenu = new AdminRoleMenuModel;
        $allMenuApi = $RoleMenu->where([])->hidden(['create_time'])->select();

        foreach ($list as $key => $value) {
            $list[$key]['apiIds'] = $this->apiIds($allMenuApi,$value['admin_role_id']);
        }
        return ['page'=>$page,'total'=>$total,'listRows'=>$listRows,'list'=>$list];
    }
    /**
     * [getList 获取菜单树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function allTree($data=[])
    {
        $hidden = ['create_time','update_time'];
        $model = $this->where($this->filter($data));
        $list = $model->hidden(['create_time'])->select();
        return $list;
    }
    /**
     * [apiIds 获取已分配的菜单id]
     * Author：上官钧墨
     * @param  [type] $list          [所有Api数据]
     * @param  [type] $admin_role_id [权限id]
     */
    private function apiIds($list,$admin_role_id){
        $arr = [];
        foreach ($list as $k => $item) {
            if ($item['admin_role_id'] == $admin_role_id) {
                array_push($arr,$item['admin_menu_id']);
            }
        }
        return $arr;
    }
    /**
     * [add 新增]
     * Author：上官钧墨
     * @param [type] $data [description]
     */
    public function add($data=[])
    {
        $newData['name'] = $data['name'];
        $newData['sort'] = $data['sort'];
        $newData['create_time'] = time();
        $newData['update_time'] = time();
        $this->startTrans();
        $admin_role_id = $this->insertGetId($newData);
        if (!$admin_role_id) {
            $this->rollback();
            $this->error = '新增失败，请重试';
            return false;
        }
        $arr = [];
        $apiIds = $data['apiIds'];
        foreach ($apiIds as $key => $admin_menu_id) {
            $arr[$key] = [
                'admin_role_id'=>$admin_role_id,
                'admin_menu_id'=>$admin_menu_id,
                'create_time'=>time()
            ];
        }
        if (count($arr)<1) {
            $this->commit();
            return true;
        }
        
        $RoleMenu = new AdminRoleMenuModel;
        $res = $RoleMenu->insertAll($arr);
        if (!$res) {
            $this->rollback();
            $this->error = '新增失败，请重试 -1';
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * [edit 编辑]
     * Author：上官钧墨
     * @param  [type] $data [更新数据]
     */
    public function edit(array $data=[])
    {
        $arr = [];
        foreach ($data['apiIds'] as $key => $admin_menu_id) {
            array_push($arr,[
                'admin_role_id'=>$data['admin_role_id'],
                'admin_menu_id'=>$admin_menu_id,
                'create_time'=>time()
            ]);
        }

        // 思路：先删除原有的关系，再新增关系
        $RoleMenu = new AdminRoleMenuModel;
        $RoleMenu->startTrans();
        $detail = $RoleMenu->where(['admin_role_id'=>$data['admin_role_id']])->select();
        if (count($detail)>0) {
            $resDel = $detail->delete();
            if (!$resDel) {
                $RoleMenu->rollback();
                $this->error = '修改失败，原关系清除失败';
                return false;
            }
        }
        if ($arr) {
            $res = $RoleMenu->insertAll($arr);
            if (!$res) {
                $RoleMenu->rollback();
                $this->error = '修改失败，请重试';
                return false;
            }
        }
        $newData['name'] = $data['name'];
        $newData['sort'] = $data['sort'];
        $newData['update_time'] = time();
        $resSave = $this->save($newData);
        if (!$resSave) {
            $this->error = '修改失败，请重试 -1';
            return false;
        }
        $RoleMenu->commit();
        return true;
    }
    /**
     * [del 删除]
     * Author：上官钧墨
     */
    public function del($data)
    {
        $menuApiModel = new AdminUserRoleModel;
        $detail = $menuApiModel->where([$this->pk=>$this[$this->pk]])->select();
        if (count($detail)>0) {
            $this->error = '删除失败，该记录已被分配，请先取消分配';
            return false;
        }
        $find = $this->detail(['pid'=>$this[$this->pk]]);
        if ($find) {
            $this->error = '删除失败，该记录下有子级';
            return false;
        }
        $RoleMenu = new AdminRoleMenuModel;
        $RoleMenu->startTrans();
        $RoleMenuDetail = $RoleMenu->where([$this->pk=>$data[$this->pk]])->select();
        if (count($RoleMenuDetail)>0) {
            $res = $RoleMenuDetail->delete();
            if (!$res) {
                $RoleMenu->rollback();
                $this->error = '删除失败，原关系清除失败';
                return false;
            }
        }
        
        $resDel = $this->delete();
        if (!$resDel) {
            $this->error = '删除失败，请重试';
            return false;
        }
        $RoleMenu->commit();
        return true;
    }

    /**
     * [detail 获取详情]
     * Author：上官钧墨
     * @param  [type] $where [条件]
     */
    public function detail($where=[], $with = [],$hidden = [])
    {
        is_array($where) ? $filter = $where : $filter[$this->pk] = (int)$where;
        return $this->get($filter, $with,$hidden);
    }



}